package com.ahui.handler.file;

import com.ahui.constant.SupportedFileTypeConst;
import com.ahui.handler.FileHandler;
import com.ahui.handler.FileHandlerFactory;
import com.ahui.util.FileUtil;
import com.ahui.util.WordUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@Slf4j
@Component
public class WordHandler implements FileHandler {

    @Override
    public void afterPropertiesSet()  {
        FileHandlerFactory.register(SupportedFileTypeConst.WORD_DOC_FILE, this);
        FileHandlerFactory.register(SupportedFileTypeConst.WORD_DOCX_FILE, this);
    }

    @Override
    public List<String> handleFile(String filePath, String tempFolder) {
        // 创建文件夹 tempPdfPath
        String tempPdfFolder = tempFolder + File.separator + FileUtil.getFileNameNoExtName(filePath);
        Path tempPdfFolderPath = Paths.get(tempPdfFolder);
        if (!Files.exists(tempPdfFolderPath) && !Files.isDirectory(tempPdfFolderPath)) {
            try {
                Files.createDirectories(tempPdfFolderPath);
            } catch (IOException e) {
                log.error("生成临时文件夹失败");
//                throw new BizRuntimeException("生成临时文件夹失败！");
            }
        }
        String pdfPath = tempPdfFolder+ File.separator + FileUtil.getFileNameNoExtName(filePath) + ".pdf";
        // 替换掉文件转PDF工具
        try {
//            Files.createDirectories(Paths.get(tempFolder));
            boolean convert = WordUtil.wordToPdf(filePath, pdfPath);
//            AssertUtils.assertTrue(convert, "文件转换PDF失败！");
        } catch (Exception e) {
            log.error("文件转换PDF失败！文件信息:{}", filePath);
//            throw new BizRuntimeException("文件转换PDF失败！文件信息:{}" + filePath);
        }

        FileHandler invokeStrategy = FileHandlerFactory.getInvokeStrategy(SupportedFileTypeConst.PDF_FILE);
        return invokeStrategy.handleFile(pdfPath, tempFolder);
    }
}
